import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shen_nai/app/user_controller.dart';
import 'package:shen_nai/entity/device_entity.dart';
import 'package:shen_nai/eventbus/event_bus.dart';
import 'package:shen_nai/pages/real_data/components/grid_item_view.dart';
import 'package:shen_nai/pages/real_data/components/real_data_head_view.dart';
import 'package:shen_nai/socket/socket_server_manage.dart';
import 'package:flutter/src/rendering/debug_overflow_indicator.dart';

//实时数据详情页
class RealDataPage extends StatefulWidget {
  const RealDataPage({Key? key}) : super(key: key);

  @override
  State<RealDataPage> createState() => _RealDataPageState();
}

class _RealDataPageState extends State<RealDataPage> {
  //设备
  late DeviceEntity _deviceEntity;
  //100模拟量
  late List<String> bit100List;
  //140开光量
  late List<String> bit140List;
  //实时数据监听
  StreamSubscription? _subscription;
  //100模拟量 json列表
  List<String> bit100JsonList = [];
   //140模拟量 json列表
  List<String> bit140JsonList = [];

  List<String> infomationNameList = [
    '电源柜',
    '炉体',
    '水冷系统',
    '水冷电缆',
    '感应圈',
    '油路系统',
    '可控硅',
    '电容',
    '部件1',
    '部件2'
  ];

  List<String> remarkList = [
    '每月对电柜内部电气接点螺丝，线路，水路进行常规检查发现有故障隐患的及时处理。',
    '每月做炉体的全面检查有故障隐患的及时排除。',
    '三个月内进行风冷系统全面检查及冷却管水垢的清理。',
    '半年至一年把水电缆拆开看看内部是否有局部断线及接触不良现象。',
    '半年至一年要检查感应圈通水是否顺畅，每组水路出水端开放看是否有水嘴腐蚀及不同程度的堵塞现象。',
    '半年至一年要检查油站是否有缺油渗油现象。',
    '假如连续更换可控硅就要检查相关阻容保护是否有问题，水套是否不平整，原则上有连续四次以上更换可控硅就要连带更换水套。',
    '半年至一年检查水嘴是否有电解及腐蚀氧化物堵路。',
    '无',
    '无'
  ];
  //检修信息
  List<String> serviceList = [];

  @override
  void initState() {
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    _deviceEntity = Get.arguments;
    bit100List = Get.find<UserController>().bit100List;
    bit140List = Get.find<UserController>().bit140List;
    for (var i = 0; i < bit100List.length; i++) {
      if (bit100List[i] != 'NULL') {
        bit100JsonList.add(jsonEncode({'name': bit100List[i], 'value': '0'}));
      }
    }
    for (var i = 0; i < bit140List.length; i++) {
      if (bit140List[i] != 'NULL') {
        bit140JsonList.add(jsonEncode({'name': bit140List[i], 'value': '0'}));
      }
    }
    _subscription = eventBus.on<EquipmentInformationEvent>().listen((event) {
      //log(event.data.serialNumber!);
      if (_deviceEntity.number == event.data.serialNumber!) {
        bit100JsonList.clear();
        bit140JsonList.clear();
        List<int> value100List = [];
        value100List.addAll(event.data.bit14List!);
        value100List.addAll(event.data.bit7List!);
        for (var i = 0; i < bit100List.length; i++) {
          if (bit100List[i] != 'NULL') {
            bit100JsonList.add(
                jsonEncode({'name': bit100List[i], 'value': value100List[i]}));
          }
        }
        for (var i = 0; i < bit140List.length; i++) {
          if (bit140List[i] != 'NULL') {
            bit140JsonList.add(jsonEncode(
                {'name': bit140List[i], 'value': event.data.switchList![i]}));
          }
        }
        setState(() {
          bit100JsonList;
          bit140JsonList;
          _deviceEntity.power1 = event.data.aPower;
          _deviceEntity.time1 = event.data.aTime;
          _deviceEntity.power2 = event.data.bPower;
          _deviceEntity.time2 = event.data.bTime;
        });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: false,
        titleSpacing: 0,
        title: Text(
          _deviceEntity.name ?? '',
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: const TextStyle(color: Colors.white),
        ),
        actions: const [
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Column(
        children: [
          RealDataHeadView(_deviceEntity),
          Expanded(
            child: ListView(
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 20),
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '模拟量',
                        style: TextStyle(color: Colors.white, fontSize: 16),
                      ),
                      InkWell(
                        onTap: () {
                          if (serviceList.isEmpty) {
                            List<int> list = [];
                            SocketServerManage().writeData(
                                'query devtime ${_deviceEntity.ID.toString()}',
                                (Uint8List value) {
                              list.addAll(value);
                              if (String.fromCharCodes(value)
                                  .contains('over')) {
                                List<String> split =
                                    String.fromCharCodes(list.sublist(0, 16))
                                        .split(' ');
                                serviceList = String.fromCharCodes(list.sublist(
                                        16,
                                        16 +
                                            int.parse(split[split.length - 1])))
                                    .split(' ');
                                _showDialog(serviceList);
                              }
                            });
                          } else {
                            _showDialog(serviceList);
                          }
                        },
                        child: const Text('检修信息',
                            style: TextStyle(
                                color: Color(0xffD29B26), fontSize: 12)),
                      )
                    ],
                  ),
                ),
                GridView.builder(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 15, vertical: 15),
                    itemCount: bit100JsonList.length,
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 1 / 0.6,
                    ),
                    itemBuilder: (context, position) =>
                        GridItemView(position, bit100JsonList[position])),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  padding: const EdgeInsets.symmetric(horizontal: 15),
                  child: const Text(
                    '开关量',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
                GridView.builder(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 15, vertical: 15),
                    itemCount: bit140JsonList.length,
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 1 / 0.6,
                    ),
                    itemBuilder: (context, position) =>
                        GridItemView(position, bit140JsonList[position]))
              ],
            ),
          ),
        ],
      ),
    );
  }
  //检修信息弹框
  _showDialog(List<String> list) {
    Get.defaultDialog(
      title: '检修信息',
      //titleStyle: TextStyle()
      content: Column(
        //crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _getDialogContentView(
              infomationNameList[0],
              list[0],
              infomationNameList[1],
              list[1],
              remarkList[0],
              remarkList[1],
              _deviceEntity.service1.toString(),
              _deviceEntity.service2.toString()),
          const SizedBox(
            height: 10,
          ),
          _getDialogContentView(
              infomationNameList[2],
              list[2],
              infomationNameList[3],
              list[3],
              remarkList[2],
              remarkList[3],
              _deviceEntity.service3.toString(),
              _deviceEntity.service4.toString()),
          const SizedBox(
            height: 10,
          ),
          _getDialogContentView(
              infomationNameList[4],
              list[4],
              infomationNameList[5],
              list[5],
              remarkList[4],
              remarkList[5],
              _deviceEntity.service5.toString(),
              _deviceEntity.service6.toString()),
          const SizedBox(
            height: 10,
          ),
          _getDialogContentView(
              infomationNameList[6],
              list[6],
              infomationNameList[7],
              list[7],
              remarkList[6],
              remarkList[7],
              _deviceEntity.service7.toString(),
              _deviceEntity.service8.toString()),
          const SizedBox(
            height: 10,
          ),
          _getDialogContentView(
              infomationNameList[8],
              list[8],
              infomationNameList[9],
              list[9],
              remarkList[8],
              remarkList[9],
              _deviceEntity.service9.toString(),
              _deviceEntity.service10.toString())
        ],
      ),
    );
  }

  //检修弹框布局
  Widget _getDialogContentView(String name1, String info1, String name2,
      String info2, String remark1, String remark2, String day1, String day2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const SizedBox(
          width: 16,
        ),
        Expanded(
            child: InkWell(
          onTap: () {
            EasyLoading.showToast(
                '检修设备信息\n设备名称:$name1：$remark1\n检修周期：$day1天\n剩余时间：$info1天',
                toastPosition: EasyLoadingToastPosition.bottom);
          },
          child: Column(
            children: [
              Text(name1),
              const SizedBox(
                height: 5,
              ),
              Text(info1)
            ],
          ),
        )),
        Expanded(
          child: InkWell(
            onTap: () {
              EasyLoading.showToast(
                  '检修设备信息\n设备名称:$name2：$remark2\n检修周期：$day2天\n剩余时间：$info2天',
                  toastPosition: EasyLoadingToastPosition.bottom);
            },
            child: Column(
              children: [
                Text(name2),
                const SizedBox(
                  height: 5,
                ),
                Text(info2)
              ],
            ),
          ),
        ),
        const SizedBox(
          width: 16,
        )
      ],
    );
  }
}
